package com.fzz.controller;

import com.fzz.domain.Admin;
import com.fzz.domain.User;
import com.fzz.service.AdminService;
import com.fzz.service.UserService;
import com.fzz.serviceImpl.AdminServiceImpl;
import com.fzz.serviceImpl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class LoginController {

    @Autowired
    private UserService userService=new UserServiceImpl();

    @Autowired
    private AdminService adminService=new AdminServiceImpl();

    @RequestMapping(value = "/")
    public String toLogin()
    {
        return "login";
    }

    @RequestMapping(value = "/login")
    public String login(HttpServletRequest request)
    {
        HttpSession session=request.getSession();
        String type = request.getParameter("type");
        switch (type)
        {
            case "用户":
                User user = userService.userLogin(request.getParameter("username"), request.getParameter("password"));
                if(user!=null)
                {
                    session.setAttribute("user",user);
                    System.out.println(user);
                    return "redirect:/user/toIndex";
                }
                break;
            case "管理员":
                String adminName=request.getParameter("username");
                String password=request.getParameter("password");
                if(session.getAttribute("admin")!=null)
                {
                    Admin admin1 = (Admin) session.getAttribute("admin");
                    adminName=admin1.getAdminName();
                    password=admin1.getPassword();
                }
                Admin admin = adminService.adminLogin(adminName,password);

                if(admin!=null)
                {
                    session.setAttribute("admin",admin);
                    return "admin";
                }
                System.out.println("Admin:"+admin);
                session.setAttribute("msg","密码或账号错误");
                break;
        }
        return "login";
    }

    @RequestMapping("admin_users")
    public String admin_user()
    {
        return "redirect:/admin/toAdmin";
    }
    @RequestMapping(value = "root_admin")
    public String root_admin()
    {
        return "root_admin";
    }
}
